<template>
    <div class="exam-container">
        <!-- 中间考试题目 -->
        <div class="main-content">
            <div v-for="(question, index) in sortedQuestions" :key="question.id" class="question-card"
                 :id="`question-${question.id}`">
                <div slot="header" class="card-header">
                    第 {{ index + 1 }} 题（{{ typeMap[question.questionType] }}
                    <span v-if="question.questionType === '4'">,多个答案用英文,符隔开</span>）
                </div>

                <div class="question-content">
                    <div class="question-text">{{ question.questionText }}</div>

                    <!-- 单选题 -->
                    <div v-if="question.questionType === '1'" class="option-group">
                        <el-radio-group v-model="answers[index]">
                            <el-radio v-for="(option, i) in parseOptions(question.chooseOption)" :key="i"
                                      :label="String.fromCharCode(65 + i)">
                                <div class="option-text">{{ String.fromCharCode(65 + i) }}. {{ option }}</div>
                            </el-radio>
                        </el-radio-group>
                    </div>

                    <!-- 多选题 -->
                    <div v-else-if="question.questionType === '2'" class="option-group">
                        <el-checkbox-group v-model="answers[index]">
                            <el-checkbox v-for="(option, i) in parseOptions(question.chooseOption)" :key="i"
                                         :label="String.fromCharCode(65 + i)">
                                <div class="option-text">{{ String.fromCharCode(65 + i) }}. {{ option }}</div>
                            </el-checkbox>
                        </el-checkbox-group>
                    </div>

                    <!-- 判断题 -->
                    <div v-else-if="question.questionType === '3'" class="option-group vertical">
                        <el-radio-group v-model="answers[index]">
                            <el-radio label="T">
                                <div class="option-text">正确</div>
                            </el-radio>
                            <el-radio label="F">
                                <div class="option-text">错误</div>
                            </el-radio>
                        </el-radio-group>
                    </div>

                    <!-- 填空题 -->
                    <div v-else-if="question.questionType === '4'" class="option-group">
                        <el-input style="font-size: 18px" type="text" v-model="answers[index]" placeholder="请输入答案"
                                  clearable></el-input>
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧导航栏 -->
        <div class="right-nav">
            <div class="nav-buttons">
                <el-button v-for="(question, index) in sortedQuestions" class="round-button"
                           @click="scrollToQuestion(index)" :key="question.id" :class="['nav-button', getButtonClass(index)]">
                    {{ index + 1 }}
                </el-button>
            </div>
            <el-button :class="['submit-btn', getSubmitButtonClass(unansweredCount)]" @click="validateBeforeSubmit">
                提交试卷(剩余{{ unansweredCount }}道题)
            </el-button>
        </div>

        <!-- 移动端底部导航栏 -->
        <div class="mobile-bottom-nav">
            <div class="mobile-nav-buttons">
                <el-button v-for="(question, index) in sortedQuestions" class="round-button"
                           @click="scrollToQuestion(index)" :key="question.id" :class="['nav-button', getButtonClass(index)]">
                    {{ index + 1 }}
                </el-button>
            </div>
            <el-button :class="['submit-btn', getSubmitButtonClass(unansweredCount)]" @click="validateBeforeSubmit">
                提交({{ unansweredCount }})
            </el-button>
        </div>
    </div>
</template>

<script>
    import request from "~/utils/request.js";
    import dayjs from 'dayjs';
    export default {
        name: 'ExamPaper',
        data() {
            return {
                studentInfo: { name: '张三' },
                typeMap: {
                    '1': '单选题',
                    '2': '多选题',
                    '3': '判断题',
                    '4': '填空题'
                },
                questions: [],
                answers: [],
                startTime: null,
                endTime: null,
            };
        },
        computed: {
            sortedQuestions() {
                return [...this.questions].sort((a, b) =>
                    a.questionType.localeCompare(b.questionType)
                );
            },
            unansweredCount() {
                return this.answers.filter((answer, index) => {
                    const q = this.sortedQuestions[index];
                    if (!q) return true;
                    if (q.questionType === '2') return answer.length === 0;
                    return !answer;
                }).length;
            }
        },
        // watch 部分增加类型校验
        watch: {
            sortedQuestions: {
                immediate: true,
                handler(newVal) {
                    this.answers = newVal.map(q => {
                        // 确保多选题初始化为数组，其他类型初始化为空字符串
                        return q.questionType === '2' ? [] : '';
                    });
                }
            }
        },
        mounted() {
            this.initAnswers();
        },
        activated() {
            this.load();

        },
        methods: {
            load() {
                this.startTime = new Date();
                request.get('/exampaper/stufindExampaperPage', {
                    params: {
                        userId: this.$store.state.user.id,
                        courseId: this.$route.query.courseId
                    }
                }).then(res => {
                    if (res.code === "200") {
                        this.questions = res.data.records;

                    }
                })
            },
            initAnswers() {
                this.answers = this.sortedQuestions.map(q =>
                    q.questionType === '2' ? [] : ''
                );
            },
            getButtonClass(index) {
                const answer = this.answers[index];
                const question = this.sortedQuestions[index];
                if (!question) return '';

                if (question.questionType === '2') {
                    return answer.length > 0 ? 'answered' : '';
                }
                return answer ? 'answered' : '';
            },
            getSubmitButtonClass(val) {
                return val === 0 ? 'endAnswer' : '';
            },
            startTimer() {
                let seconds = 0;
                this.timer = setInterval(() => {
                    seconds++;
                    const hours = Math.floor(seconds / 3600);
                    const minutes = Math.floor((seconds % 3600) / 60);
                    const secs = seconds % 60;
                    this.elapsedTime = [hours, minutes, secs]
                        .map(n => n.toString().padStart(2, '0'))
                        .join(':');
                }, 1000);
            },
            parseOptions(options) {
                try {
                    const obj = JSON.parse(options);
                    return Object.keys(obj).sort().map(k => obj[k]);
                } catch {
                    return [];
                }
            },
            scrollToQuestion(index) {
                const questionId = this.sortedQuestions[index].id;
                const element = document.getElementById(`question-${questionId}`);
                if (element) {
                    element.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }
            },
            validateBeforeSubmit() {
                if (this.unansweredCount > 0) {
                    this.$message.warning(`还有${this.unansweredCount}题未完成`);
                    return;
                }
                this.submitExam();
            },
            submitExam() {
                this.endTime = new Date();
                this.$confirm('确定要提交试卷吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const formattedAnswers = this.sortedQuestions.map((q, i) => ({
                        id: q.id,
                        answer: q.questionType === '2'
                            ? JSON.stringify(this.answers[i])
                            : this.answers[i]
                    }));
                    console.log('提交答案:', formattedAnswers);
                    const startTimeStr = dayjs(this.startTime).format('YYYY-MM-DD HH:mm:ss');
                    const endTimeStr = dayjs(this.endTime).format('YYYY-MM-DD HH:mm:ss');
                    request.post('/exam-answer-detail/stuSubmitExampaper', {
                        courseId: this.$route.query.courseId,
                        stuId: this.$store.state.user.id,
                        answerList: formattedAnswers,
                        startTime: startTimeStr,
                        endTime: endTimeStr,
                    }).then(res => {
                        if (res.code === "200") {
                            this.$message.success('提交成功！');
                            this.$router.push({path: "/exam/result", query: {courseId: this.$route.query.courseId}})
                        }
                    })

                    // this.$message.success('提交成功！');
                    // this.$router.push('/exam/result');
                });
            }
        }
    };
</script>

<!-- 保留原有样式，添加answer.vue的自定义样式 -->
<style scoped>
    /* 整体布局 */
    .exam-container {
        display: flex;
        height: 83vh;
        background: #f7f8fa;
    }

    /* 左侧考生信息 */
    .user-info {
        width: 200px;
        padding: 20px;
        background: white;
        box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
        border-right: 1px solid #ebedf0;
    }

    /* 中间题目区 */
    .main-content {
        flex: 1;
        padding: 20px;
        overflow-y: auto;
        /* 启用垂直滚动 */
        max-height: 100vh;
    }

    /* 右侧导航栏 */
    .right-nav {
        width: 200px;
        padding: 20px;
        background: white;
        box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
        border-left: 1px solid #ebedf0;
        display: flex;
        flex-direction: column;
    }

    /* 调整导航按钮布局 */
    .nav-buttons {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 10px;
        overflow-y: auto;
        flex: 1;
        margin-bottom: 20px;
    }

    .submit-btn {
        width: 100%;
        padding: 12px;
        font-size: 16px;
        margin-top: auto;
        /* 使提交按钮始终在底部 */
    }

    /* 原底部导航栏样式移除 */
    .bottom-nav {
        display: none;
    }

    /* 题目卡片微调 */
    .question-card {
        border-radius: 15px;
        font-size: 20px;
        background-color: white;
        padding: 15px;
        margin-bottom: 20px;
        max-width: 800px;
        /* 控制题目最大宽度 */
        margin-left: auto;
        margin-right: auto;
        box-sizing: border-box;
    }

    .question-text {
        font-size: 18px;
        color: #333;
        line-height: 1.5;
        margin: 16px 0;
        word-wrap: break-word;
        overflow-wrap: break-word;
    }

    /* 选项文本样式 */
    .option-text {
        font-size: 18px;
        word-wrap: break-word;
        overflow-wrap: break-word;
        white-space: normal;
        line-height: 1.4;
    }

    .warning {
        color: #e6a23c;
    }

    /* 修改按钮为圆形 */
    .round-button {
        border-radius: 50%;
        width: 30px;
        height: 30px;
        padding: 0;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    /* 回答后按钮颜色为绿色 */
    .answered {
        background-color: #67c23a;
        border-color: #67c23a;
        color: white;
    }

    .endAnswer {
        background-color: #6699ff;
        border-color: #6699ff;
        color: white;
    }

    /* 移动端底部导航栏 - 默认隐藏 */
    .mobile-bottom-nav {
        display: none;
    }

    /* 移动端样式 */
    @media (max-width: 768px) {
        .exam-container {
            flex-direction: column;
            height: auto;
            min-height: 100vh;
            /*padding-bottom: 50px; !* 为底部导航栏留出空间 *!*/
        }

        .right-nav {
            display: none; /* 在移动端隐藏右侧导航栏 */
        }

        .main-content {
            /*padding: 15px;*/
            max-width: 100%;
            margin-bottom: 0;
            box-sizing: border-box;
        }

        .question-card {
            max-width: 100%;
            font-size: 16px;
            padding: 12px;
            margin-bottom: 15px;
            width: 100%;
            box-sizing: border-box;
        }

        .question-text {
            font-size: 16px;
            line-height: 1.4;
        }

        /* 移动端选项文本样式 */
        .option-text {
            font-size: 16px;
            line-height: 1.4;
            white-space: normal;
            word-break: break-word;
            width: 100%;
        }

        /* 移动端底部导航栏 */
        .mobile-bottom-nav {
            display: flex;
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
            padding: 10px 15px;
            z-index: 900;
            align-items: center;
            justify-content: space-between;
            box-sizing: border-box;
        }

        .mobile-nav-buttons {
            display: flex;
            overflow-x: auto;
            flex: 1;
            margin-right: 10px;
            padding: 12px 0;
        }

        .mobile-nav-buttons .round-button {
            flex-shrink: 0;
            margin-right: 8px;
        }

        .mobile-bottom-nav .submit-btn {
            width: auto;
            min-width: 100px;
            padding: 8px 12px;
            font-size: 14px;
            white-space: nowrap;
        }

        /* 优化选项显示 */
        .option-group {
            font-size: 16px;
            width: 100%;
        }

        /* 调整单选/多选框大小和布局 */
        .el-radio, .el-checkbox {
            margin-bottom: 8px;
            width: 100%;
            align-items: flex-start;
        }

        .el-radio ::v-deep .el-radio__label,
        .el-checkbox ::v-deep .el-checkbox__label {
            white-space: normal;
            word-break: break-word;
            width: calc(100% - 20px);
            display: inline-block;
            vertical-align: top;
        }

        /* 填空题输入框优化 */
        .el-input {
            font-size: 16px !important;
            width: 100%;
        }

        /* 确保选项组内元素正确换行 */
        .el-radio-group,
        .el-checkbox-group {
            width: 100%;
        }
    }

    /* 超小屏幕优化 */
    @media (max-width: 480px) {
        .main-content {
            padding: 10px;
        }

        .question-card {
            padding: 10px;
            margin-bottom: 12px;
        }

        .mobile-bottom-nav {
            padding: 10px 10px;
        }

        .mobile-bottom-nav .submit-btn {
            min-width: 80px;
            padding: 20px 10px;
            font-size: 13px;
        }

        .round-button {
            width: 28px;
            height: 28px;
            font-size: 12px;
        }

        .option-text {
            font-size: 15px;
        }
    }

    /* 针对极窄屏幕的额外优化 */
    @media (max-width: 360px) {
        .question-text {
            font-size: 15px;
        }

        .option-text {
            font-size: 14px;
        }

        .main-content {
            padding: 8px;
        }
    }
</style>
